﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace GN.Pay.Utils.Security
{
    /// <summary>
    /// DES 帮助
    /// </summary>
    public static class DesUtils
    {
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="sourceString">源字符</param>
        /// <param name="key">密</param>
        /// <param name="iv">向量</param>
        /// <returns></returns>
        public static string Encrypt(string sourceString, string key, string iv)
        {
            byte[] btKey = Encoding.UTF8.GetBytes(key);
            byte[] btIV = Encoding.UTF8.GetBytes(iv);
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = null;
                try
                {
                    byte[] inData = Encoding.UTF8.GetBytes(sourceString);
                    cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write);
                    cs.Write(inData, 0, inData.Length);
                    cs.FlushFinalBlock();
                    return Convert.ToBase64String(ms.ToArray());
                }
                finally
                {
                    ms.Dispose();
                    if (cs != null)
                    {
                        cs.Dispose();
                    }
                }
            }

        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="encryptedString">加密字符</param>
        /// <param name="key">密</param>
        /// <param name="iv">向量</param>
        /// <returns></returns>
        public static string Decrypt(string encryptedString, string key, string iv)
        {
            byte[] btKey = Encoding.UTF8.GetBytes(key);
            byte[] btIV = Encoding.UTF8.GetBytes(iv);
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = null;
                try
                {
                    byte[] inData = Convert.FromBase64String(encryptedString);
                    cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write);
                    cs.Write(inData, 0, inData.Length);
                    cs.FlushFinalBlock();
                    return Encoding.UTF8.GetString(ms.ToArray());
                }
                finally
                {
                    ms.Dispose();
                    if (cs != null)
                    {
                        cs.Dispose();
                    }
                }
            }
        }
    }
}
